package com.cedifie.lendapp.ui.user.act

import android.view.Gravity
import android.view.View
import androidx.recyclerview.widget.DefaultItemAnimator
import androidx.recyclerview.widget.LinearLayoutManager
import com.cedifie.lendapp.R
import com.cedifie.lendapp.databinding.ActPermissionReasonListBinding
import com.cedifie.lendapp.http.HttpHelper
import com.cedifie.lendapp.mvp.RestartAct
import com.cedifie.lendapp.ui.user.adapter.CedPermissionReasonAdapter
import com.cedifie.lendapp.utils.decoration.LinearSpacingItemDecoration
import com.cedifie.lendapp.utils.dialog.TipsDialog
import com.cedifie.lendapp.utils.event.CedEventType
import com.cedifie.lendapp.utils.helper.PermissionHelper
import com.cedifie.lendapp.utils.helper.SharedHelper
import com.cedifie.lib_permission.OnPermissionCallback
import com.cedifie.lib_permission.Permission
import com.cedifie.lib_permission.XXPermissions
import com.lib.base.utils.DensityUtils
import org.json.JSONObject

/**
 * 权限声明列表
 */
class CedPermissionReasonAct : RestartAct() {
    private lateinit var binding: ActPermissionReasonListBinding
    var reasonAdapter: CedPermissionReasonAdapter? = null

    override fun getCedRootView(): View {
        binding = ActPermissionReasonListBinding.inflate(layoutInflater)
        return binding.root
    }

    override fun initCedView() {
        setCedTitleBarVisibility(View.VISIBLE)
        setCedTextTitle(getString(R.string.permissions_title))
        setCedTextTitleGravity(Gravity.CENTER)
        setCedRightBtnRes(com.lib.base.R.mipmap.icon_kefu_black)

        initCedPermissionReasonRecyclerView()
    }

    override fun initCedListener() {
        //联系客服
        rootViewBinding.ivFun.setOnClickListener {
            onIntent(CedUserFeedbackAct::class.java)
            HttpHelper.addCedEventAction(CedEventType.CLICK.CED_CLICK_CUSTOMER, "Permission Page")
        }

        //拒绝
        binding.btnDeny.setOnClickListener {
            SharedHelper.saveCedSPData(SharedHelper.CED_SPKEY.CEDIFIE_PERMISSION_REASON_TYPE,-1)
            HttpHelper.addCedEventAction(CedEventType.CLICK.CED_CLICK_PERMISSION_DENY,"Permission Page")

            val intent = intent
            intent.putExtra("isPermissionAgree",false)
            setResult(RESULT_OK,intent)
            finish()
        }

        //同意权限
        binding.btnAgree.setOnClickListener {
            HttpHelper.addCedEventAction(CedEventType.CLICK.CED_CLICK_PERMISSION_AGREE,"Permission Page")
            if (!binding.checkBox.isChecked){
                showPermissionAgreedDialog()
                return@setOnClickListener
            }
            SharedHelper.saveCedSPData(SharedHelper.CED_SPKEY.CEDIFIE_PERMISSION_REASON_TYPE,1)
            requestCedPermission()
        }
    }

    override fun initCedData() {
        val list = arrayListOf<JSONObject>()
        //权限提示Item
        val noticeItem = JSONObject()
        noticeItem.put("itemType","noticeItem")
        list.add(noticeItem)

        list.add(PermissionHelper.getCedSmsPermissionItem())
        list.add(PermissionHelper.getCedDevicePermissionItem())
        list.add(PermissionHelper.getCedAppListPermissionItem())
        list.add(PermissionHelper.getCedCameraPermissionItem())
        list.add(PermissionHelper.getCedStoragePermissionItem())
        list.add(PermissionHelper.getCedContactPermissionItem())
        list.add(PermissionHelper.getCedPhotoAlbumPermissionItem())
        reasonAdapter?.data = list
    }

    /**
     * 初始化明细列表
     */
    private fun initCedPermissionReasonRecyclerView() {
        val decoration = DensityUtils.dp2px(16f)
        binding.recyclerView.addItemDecoration(LinearSpacingItemDecoration(decoration,decoration,decoration,decoration))
        binding.recyclerView.layoutManager = LinearLayoutManager(this)
        reasonAdapter = CedPermissionReasonAdapter(binding.recyclerView)
        binding.recyclerView.adapter = reasonAdapter
        binding.recyclerView.itemAnimator = DefaultItemAnimator()
    }

    /**
     * 阅读与同意
     */
    private fun showPermissionAgreedDialog(){
        val tipsDialog = TipsDialog(this,"Permission Page",object : TipsDialog.IDialogCallback{
            override fun onClick(view: View?) {
                if (view?.id == R.id.btnRight){
                    binding.checkBox.isChecked = true
                    binding.btnAgree.callOnClick()
                }
            }
        })
        tipsDialog.setCancelable(true)
        tipsDialog.setCanceledOnTouchOutside(false)
        tipsDialog.show()
        tipsDialog.setButtonLeftText(getString(R.string.btn_cancel))
        tipsDialog.setButtonRightText(getString(R.string.btn_ok))
        tipsDialog.setTipsTitle(getString(R.string.tips_kind))
        tipsDialog.setTips(getString(R.string.permission_agree_tips))
    }

    /**
     * 申请权限
     */
    private fun requestCedPermission(){
        XXPermissions.with(this)
            .permission(Permission.READ_SMS)
            .request(object: OnPermissionCallback {
                override fun onGranted(permissions: MutableList<String>, p1: Boolean) {
                    if (p1){
                        var permissionString = ""
                        permissions.forEach {
                            permissionString = "$permissionString$it,"
                        }
                        HttpHelper.addCedEventAction(CedEventType.CLICK.CED_CLICK_PERMISSION_SYSTEM_AGREE,permissionString.substring(0,permissionString.length - 1))

                        val intent = intent
                        intent.putExtra("isPermissionAgree",true)
                        setResult(RESULT_OK,intent)
                        finish()
                    }
                }
                override fun onDenied(permissions: MutableList<String>, doNotAskAgain: Boolean) {
                    var permissionString = ""
                    permissions.forEach {
                        permissionString = "$permissionString$it,"
                    }
                    HttpHelper.addCedEventAction(CedEventType.CLICK.CED_CLICK_PERMISSION_SYSTEM_DENY,permissionString.substring(0,permissionString.length - 1))
                    XXPermissions.startPermissionActivity(this@CedPermissionReasonAct,Permission.READ_SMS)
                }
            })
    }

    override fun onStart() {
        super.onStart()
        HttpHelper.addCedEventAction(CedEventType.PAGE.CED_PAGE_PERMISSION_START,"")
    }

    override fun onDestroy() {
        super.onDestroy()
        HttpHelper.addCedEventAction(CedEventType.PAGE.CED_PAGE_PERMISSION_END,"")
    }
}